<template>
    <div style="margin-left: 15px; margin-right: 15px">
        <el-row style="height: 100%">
            <el-col :span="11">
                <vxe-grid ref="xGridPro" v-bind="gridOptionsProvider" v-on="gridEventsPro" :params="searchInfoProvider">
                    <template #action="{ row }">
                        <vxe-button icon="vxe-iconfont-edit" title="编辑" circle @click="proEditRowEvent(row)"></vxe-button>
                        <vxe-button icon="vxe-icon-delete" title="删除" circle @click="proRemoveRowEvent(row)"></vxe-button>
                    </template>
                </vxe-grid>
            </el-col>
            <el-col :span="13">
                <vxe-grid ref="xGridPanel" v-bind="gridOptionsPanel" v-on="gridEventsPanel" :params="searchInfoPanel" @printTemplateDesign="printTemplateDesign" @edit-actived="editActivedEvent">
                    <template #action="{ row }">
                        <vxe-button icon="vxe-iconfont-edit" title="编辑" circle @click="panelEditRowEvent(row)"></vxe-button>
                        <vxe-button icon="vxe-icon-delete" title="删除" status="danger" circle @click="panelRemoveRowEvent(row)"></vxe-button>
                    </template>
                    <template #providerId_edit="{ row }">
                        <vxe-input v-model="row.providerId" :disabled="row.providerId ? true : false"></vxe-input>
                    </template>
                </vxe-grid>
            </el-col>
        </el-row>
        <VxeTemplatePanel :storeData="printStoreData" ref="designTemplate" :vxeTable="xGridPanel"></VxeTemplatePanel>
        <PanelModal :modelValue="panelModalVisible" :aceValue="modalValue" :record="panelRecord" @update:modelValue="(newValue) => (panelModalVisible = newValue)" @update:aceValue="(newValue) => (modalValue = newValue)" @close="xGridPanel.commitProxy('reload')"> </PanelModal>
        <ProviderModal :modelValue="providerModalVisible" :aceValue="modalValuePro" :record="panelRecordPro" @update:aceValue="(newValue) => (modalValuePro = newValue)" @update:modelValue="(newValue) => (providerModalVisible = newValue)" @close="xGridPro.commitProxy('reload')"> </ProviderModal>
        <ImportTable ref="importRef" @ok="handleQuery" />
    </div>
</template>

<script lang="ts">
    import { defineComponent, ref, unref, reactive } from "vue";
    import { VXETable } from "../../../../packages/all";
    import { VxeGridEvents } from "../../../../types/all";
    import { VxeGridInstance, VxeGridProps } from "../../../../types/index";
    import XEUtils from "xe-utils";
    import { VxeGridListeners } from "../../../../types/index";
    import useBaseApi from "@/api/base/index";
    import { ElLoading, ElMessageBox, ElMessage } from "element-plus";
    import PanelModal from "./PanelModal.vue";
    import ProviderModal from "./ProviderModal.vue";
    import ImportTable from "./importTable.vue";
    export default defineComponent({
        components: {
            PanelModal,
            ProviderModal,
            ImportTable,
        },
        setup() {
            const { callGetOne: callGetOnePro, callBatchModify: callBatchModifyPro, callBatchSave: callBatchSavePro, callPageList: callPagePro, callRemoves: callRemovesPro } = useBaseApi("/print/printProvider");
            const { callGetOne, callModify, callBatchModify, callBatchSave, callPageList, callRemoves } = useBaseApi("/print/printPanel");
            const xGridPro = ref({} as VxeGridInstance);
            const xGridPanel = ref({} as VxeGridInstance);
            const designTemplate = ref();
            const panelModalVisible = ref(false);
            const providerModalVisible = ref(false);
            const modalValuePro = ref();
            const panelRecordPro = ref();
            const modalValue = ref();
            const panelRecord = ref();
            const importRef = ref();
            function getTableActionPro() {
                const tableAction = unref(xGridPro);
                if (!tableAction) {
                    throw new Error("tableAction is null");
                }
                return tableAction;
            }
            function getTableActionPanel() {
                const tableAction = unref(xGridPanel);
                if (!tableAction) {
                    throw new Error("tableAction is null");
                }
                return tableAction;
            }
            const searchInfoPanel = reactive<any>({
                bidId: 0,
            });
            const searchInfoProvider = reactive<any>({
                bidId: 0,
            });
            const gridOptionsProvider = reactive<VxeGridProps>({
                border: true,
                resizable: true,
                showHeaderOverflow: true,
                showOverflow: true,
                highlightHoverRow: true,
                keepSource: true,
                id: "2",
                height: "auto",
                rowId: "providerId",
                customConfig: {
                    storage: true,
                },
                sortConfig: {
                    trigger: "cell",
                    remote: true,
                },
                filterConfig: {
                    remote: true,
                },
                pagerConfig: {
                    pageSize: 10,
                    pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
                    perfect: true,
                },
                formConfig: {
                    titleWidth: 100,
                    titleAlign: "right",
                    items: [
                        {
                            field: "providerId",
                            title: "面板ID",
                            span: 9,
                            itemRender: { name: "$input", props: { placeholder: "请输入面板ID" } },
                        },
                        {
                            field: "providerTitle",
                            title: "面板名称",
                            span: 9,
                            itemRender: { name: "$input", props: { placeholder: "请输入面板名称" } },
                        },

                        {
                            itemRender: {
                                name: "$buttons",
                                children: [
                                    {
                                        props: {
                                            type: "submit",
                                            content: "查询",
                                            status: "primary",
                                        },
                                    },
                                    {
                                        props: {
                                            type: "reset",
                                            content: "重置",
                                        },
                                    },
                                ],
                            },
                        },
                    ],
                },
                toolbarConfig: {
                    refresh: true,
                    zoom: true,
                    custom: true,
                    // slots: {
                    //     buttons: "toolbar_buttons",
                    // },
                    buttons: [
                        { code: "insert_actived", name: "新增", status: "primary" },
                        { code: "save", name: "保存", status: "success", disabled: false },
                        { code: "delete", name: "删除", status: "danger", visible: true },
                        { code: "bidConfig", name: "配置", status: "info" },
                    ],
                },
                proxyConfig: {
                    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
                    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
                    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
                    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
                    // 对应响应结果 { result: [], page: { total: 100 } }
                    props: {
                        result: "rows", // 配置响应结果列表字段
                        total: "total", // 配置响应结果总页数字段
                    },
                    ajax: {
                        // 接收 Promise
                        query: ({ page, sorts, filters, form, params }: any) => {
                            const queryParams: any = Object.assign({}, page, form);
                            // 处理排序条件
                            const orderByColumn = <Array<String>>[];
                            const isAsc = <Array<Boolean>>[];
                            sorts.forEach((m: any) => {
                                orderByColumn.push(m.field);
                                isAsc.push(m.order);
                            });
                            queryParams.orderByColumn = orderByColumn.join(",");
                            queryParams.isAsc = isAsc.join(",");
                            // 处理筛选条件
                            filters.forEach(({ property, values }: any) => {
                                queryParams[property] = values.join(",");
                            });
                            return callPagePro({
                                ...queryParams,
                                ...params,
                            }).then((response) => {
                                return response;
                            });
                        },
                        delete: async ({ body }: any) => {
                            await callRemovesPro(body.removeRecords.map((item: any) => item.providerId));
                        },
                        save: async ({ body }: any) => {
                            if (body.updateRecords.length > 0 && body.insertRecords.length > 0) {
                                await callBatchModifyPro(body.updateRecords);
                                await callBatchSavePro(body.insertRecords);
                                return;
                            }
                            if (body.updateRecords.length > 0) {
                                return await callBatchModifyPro(body.updateRecords);
                            }
                            if (body.insertRecords.length > 0) {
                                return await callBatchSavePro(body.insertRecords);
                            }
                        },
                    },
                },
                columns: [
                    { type: "checkbox", width: 50 },
                    {
                        field: "providerId",
                        title: "面板ID",
                        sortable: true,
                    },
                    {
                        field: "providerTitle",
                        title: "面板名称",
                        sortable: true,
                        editRender: { name: "input", attrs: { placeholder: "请输入面板名称" } },
                    },

                    {
                        field: "providerData",
                        title: "面板数据",
                        width: 160,
                    },
                    {
                        field: "remark",
                        title: "备注",
                        editRender: { name: "input", attrs: { placeholder: "请输入备注" } },
                    },
                    {
                        field: "createBy",
                        title: "创建人",
                    },
                    {
                        field: "createTime",
                        title: "创建时间",
                        visible: false,
                        sortable: true,
                        formatter({ cellValue }: any) {
                            return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                        },
                    },
                    {
                        field: "updateBy",
                        title: "修改人",
                    },
                    {
                        field: "updateTime",
                        title: "修改时间",
                        visible: false,
                        sortable: true,
                        formatter({ cellValue }: any) {
                            return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                        },
                    },
                    {
                        title: "操作",
                        width: 120,
                        align: "center",
                        fixed: "right",
                        slots: { default: "action" },
                    },
                ],
                editRules: {
                    providerTitle: [{ required: true, message: "面板名称必填" }],
                },
                editConfig: {
                    trigger: "click",
                    mode: "row",
                    showStatus: true,
                },
            });
            const gridOptionsPanel = reactive<VxeGridProps>({
                border: true,
                resizable: true,
                showHeaderOverflow: true,
                showOverflow: true,
                highlightHoverRow: true,
                keepSource: true,
                id: "3",
                height: "auto",
                rowId: "panelId",
                customConfig: {
                    storage: true,
                },
                sortConfig: {
                    trigger: "cell",
                    remote: true,
                },
                filterConfig: {
                    remote: true,
                },
                pagerConfig: {
                    pageSize: 10,
                    pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
                    perfect: true,
                },
                formConfig: {
                    titleWidth: 100,
                    titleAlign: "right",
                    items: [
                        {
                            field: "panelId",
                            title: "模板ID",
                            span: 9,
                            itemRender: { name: "$input", props: { placeholder: "请输入模板ID" } },
                        },
                        {
                            field: "panelTitle",
                            title: "模板名称",
                            span: 9,
                            itemRender: { name: "$input", props: { placeholder: "请输入模板名称" } },
                        },
                        {
                            itemRender: {
                                name: "$buttons",
                                children: [
                                    {
                                        props: {
                                            type: "submit",
                                            content: "查询",
                                            status: "primary",
                                        },
                                    },
                                    {
                                        props: {
                                            type: "reset",
                                            content: "重置",
                                        },
                                    },
                                ],
                            },
                        },
                    ],
                },
                toolbarConfig: {
                    refresh: true,
                    zoom: true,
                    custom: true,
                    // slots: {
                    //     buttons: "toolbar_buttons",
                    // },
                    buttons: [
                        { code: "insert_actived", name: "新增", status: "primary" },
                        { code: "save", name: "保存", status: "success", disabled: false },
                        { code: "delete", name: "删除", status: "danger", visible: true },
                        { code: "jsonEdit", name: "JSON", status: "info" },
                    ],
                },
                proxyConfig: {
                    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
                    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
                    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
                    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
                    // 对应响应结果 { result: [], page: { total: 100 } }
                    props: {
                        result: "rows", // 配置响应结果列表字段
                        total: "total", // 配置响应结果总页数字段
                    },
                    ajax: {
                        // 接收 Promise
                        query: ({ page, sorts, filters, form, params }: any) => {
                            const queryParams: any = Object.assign({}, page, form);
                            // 处理排序条件
                            const orderByColumn = <Array<String>>[];
                            const isAsc = <Array<Boolean>>[];
                            sorts.forEach((m: any) => {
                                orderByColumn.push(m.field);
                                isAsc.push(m.order);
                            });
                            queryParams.orderByColumn = orderByColumn.join(",");
                            queryParams.isAsc = isAsc.join(",");
                            // 处理筛选条件
                            filters.forEach(({ property, values }: any) => {
                                queryParams[property] = values.join(",");
                            });
                            return callPageList({
                                ...queryParams,
                                ...params,
                            }).then((response) => {
                                return response;
                            });
                        },
                        delete: async ({ body }: any) => {
                            await callRemoves(body.removeRecords.map((item: any) => item.panelId));
                        },
                        save: async ({ body }: any) => {
                            if (body.updateRecords.length > 0 && body.insertRecords.length > 0) {
                                await callBatchModify(body.updateRecords);
                                await callBatchSave(body.insertRecords);
                                return;
                            }
                            if (body.updateRecords.length > 0) {
                                return await callBatchModify(body.updateRecords);
                            }
                            if (body.insertRecords.length > 0) {
                                return await callBatchSave(body.insertRecords);
                            }
                        },
                    },
                },
                checkboxConfig: {
                    labelField: "ID",
                    reserve: true,
                    highlight: true,
                    range: true,
                },
                columnConfig: {
                    resizable: true,
                },
                columns: [
                    { type: "checkbox", width: 50 },
                    {
                        field: "panelId",
                        title: "模板ID",
                        sortable: true,
                    },
                    {
                        field: "panelTitle",
                        title: "模板名称",
                        sortable: true,
                        editRender: { name: "input", attrs: { placeholder: "请输入模板名称" } },
                    },
                    {
                        field: "panelPaperWidth",
                        title: "纸张宽度",
                    },
                    {
                        field: "panelPaperHeight",
                        title: "纸张高度",
                    },
                    {
                        field: "providerId",
                        title: "面板ID",
                        editRender: { name: "input", attrs: { placeholder: "请输入面板ID" } },
                        slots: { edit: "providerId_edit" },
                    },
                    {
                        field: "remark",
                        title: "备注",
                        editRender: { name: "input", attrs: { placeholder: "请输入备注" } },
                    },

                    {
                        field: "createBy",
                        title: "创建人",
                        sortable: true,
                    },
                    {
                        field: "createTim",
                        title: "创建时间",
                        visible: false,
                        sortable: true,
                        formatter({ cellValue }: any) {
                            return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                        },
                    },
                    {
                        field: "updateBy",
                        title: "修改人",
                    },
                    {
                        field: "updateTime",
                        title: "修改时间",
                        visible: false,
                        sortable: true,
                        formatter({ cellValue }: any) {
                            return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                        },
                    },
                    {
                        title: "操作",
                        width: 120,
                        align: "center",
                        fixed: "right",
                        slots: { default: "action" },
                    },
                ],
                editRules: {
                    panelTitle: [{ required: true, message: "模板名称必须填写" }],
                },
                editConfig: {
                    trigger: "click",
                    mode: "row",
                    showStatus: true,
                },
            });

            const gridEventsPro: VxeGridListeners = {
                async toolbarButtonClick({ code }) {
                    console.log("toolbarButtonClick", code);
                    switch (code) {
                        case "bidConfig": {
                            const list = await getTableActionPro().getCheckboxRecords();
                            if (list.length == 0) {
                                ElMessageBox.alert("请选择一条数据", "错误提示", { confirmButtonText: "确定", type: "warning", draggable: true });
                                return;
                            }
                            if (list.length > 1) {
                                ElMessageBox.alert("只能选择一条数据", "错误提示", { confirmButtonText: "确定", type: "warning", draggable: true });
                                return;
                            }
                            panelRecordPro.value = list[0];
                            try {
                                modalValuePro.value = JSON.stringify(null != list[0]["providerData"] ? JSON.parse(list[0]["providerData"]) : null, null, 2);
                                providerModalVisible.value = true;
                            } catch (e) {
                                ElMessageBox.confirm("json数据转换失败,是否继续打开", "错误提示", {
                                    confirmButtonText: "确定",
                                    cancelButtonText: "取消",
                                    type: "warning",
                                })
                                    .then(() => {
                                        providerModalVisible.value = true;
                                        modalValuePro.value = null;
                                    })
                                    .catch(() => {});
                            }
                        }
                    }
                },
                toolbarToolClick(code) {
                    console.log("toolbarToolClick", code);
                },
            };

            const gridEventsPanel: VxeGridListeners = {
                async toolbarButtonClick({ code }) {
                    const $grid = xGridPanel.value;
                    console.log("toolbarButtonClick", code);
                    switch (code) {
                        case "jsonEdit": {
                            const list = await getTableActionPanel().getCheckboxRecords();
                            if (list.length == 0) {
                                ElMessageBox.alert("请选择一条数据", "错误提示", { confirmButtonText: "确定", type: "warning", draggable: true });
                                return;
                            }
                            if (list.length > 1) {
                                ElMessageBox.alert("只能选择一条数据", "错误提示", { confirmButtonText: "确定", type: "warning", draggable: true });
                                return;
                            }
                            panelRecord.value = list[0];
                            try {
                                modalValue.value = JSON.stringify(null != list[0]["panelData"] ? JSON.parse(list[0]["panelData"]) : null, null, 2);
                                panelModalVisible.value = true;
                            } catch (e) {
                                ElMessageBox.confirm("json数据转换失败,是否继续打开", "错误提示", {
                                    confirmButtonText: "确定",
                                    cancelButtonText: "取消",
                                    type: "warning",
                                })
                                    .then(() => {
                                        panelModalVisible.value = true;
                                        modalValue.value = null;
                                    })
                                    .catch(() => {});
                            }
                        }
                    }
                },
                toolbarToolClick({ code }) {
                    const $grid = xGridPanel.value;
                    switch (code) {
                        case "myPrint": {
                            $grid.print();
                            break;
                        }
                    }
                },
            };

            const selectRecords = ref(0);

            const proEditRowEvent = (row: any) => {
                panelRecordPro.value = row;
                try {
                    modalValuePro.value = JSON.stringify(JSON.parse(row["providerData"]), null, 2);
                    providerModalVisible.value = true;
                } catch (e) {
                    ElMessageBox.confirm("json数据转换失败,是否继续打开", "错误提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    })
                        .then(() => {
                            providerModalVisible.value = true;
                            modalValuePro.value = null;
                        })
                        .catch(() => {});
                }
            };
            const proSaveRowEvent = async () => {};
            // 面板行内删除
            const proRemoveRowEvent = async (row: any) => {
                const loading = ElLoading.service({
                    background: "rgba(0, 0, 0, 0.7)",
                });
                await callRemovesPro(row.providerId);
                loading.close();
                xGridPro.value.commitProxy("reload");
            };

            // 模板编辑（没有绑定面板时需要选择一个面板进行绑定）
            const panelEditRowEvent = async (row: any) => {
                const list = await xGridPro.value.getCheckboxRecords();
                if (!row.providerId) {
                    if (list.length == 0) {
                        console.log("请选择数据");
                        ElMessageBox.alert("请选择数据一个面板数据", "信息提示", { confirmButtonText: "确定", type: "warning", draggable: true });
                        return;
                    } else if (list.length > 1) {
                        ElMessageBox.alert("只能选择一个面板数据", "信息提示", { confirmButtonText: "确定", type: "warning", draggable: true });
                        return;
                    } else {
                        row.providerId = list[0].providerId;
                        printStoreData.designPrint.providerData = JSON.parse(list[0]["providerData"]);
                    }
                } else {
                    await callGetOnePro(row.providerId).then((res) => {
                        if (res["code"] == 200) {
                            printStoreData.designPrint.providerData = JSON.parse(res["data"]["providerData"]);
                        }
                    });
                }
                printStoreData.designPrint.panelData = JSON.parse(row["panelData"]);
                printStoreData.from = row;
                printStoreData.visible = true;
            };
            const panelSaveRowEvent = async () => {};
            const panelRemoveRowEvent = async (row: any) => {
                const loading = ElLoading.service({
                    background: "rgba(0, 0, 0, 0.7)",
                });
                await callRemoves(row.panelId).then((res) => {
                    if (res["code"] == 200) {
                        ElMessage({
                            message: res["msg"],
                            type: "success",
                        });
                    } else {
                        ElMessage({
                            message: res["msg"],
                            type: "error",
                        });
                    }
                });
                loading.close();
                xGridPanel.value.commitProxy("reload");
            };
            const printStoreData = reactive({
                inited: false,
                name: "",
                hasFooter: false,
                visible: false,
                isFooter: false,
                designPrint: {
                    providerData: {},
                    panelData: {},
                },
                // 传输给弹窗的数据，该数据会在隐藏和显示弹窗的时候返回
                from: {},
                //保存调用接口
                saveDesign: async (value: any) => {
                    await callModify({ ...value.from, panelData: JSON.stringify(value.templateData) }).then((res) => {
                        if (res["code"] == 200) {
                            ElMessage({
                                message: res["msg"],
                                type: "success",
                            });
                        } else {
                            ElMessage({
                                message: res["msg"],
                                type: "error",
                            });
                        }
                    });
                    getTableActionPanel().commitProxy("query");
                },
            });
            const printTemplateDesign = (value: any) => {
                console.log("模板", value);
            };

            // 模板修改时验证面板id是否可修改（面板id存在时禁止修改）
            const disabledProviderId = ref(false);
            const editActivedEvent: VxeGridEvents.EditDisabled = ({ row }) => {
                disabledProviderId.value = null != row["providerId"];
            };
            function handleQuery() {
                getTableActionPro().commitProxy("reload");
            }
            return {
                xGridPro,
                xGridPanel,
                searchInfoPanel,
                searchInfoProvider,
                gridOptionsProvider,
                gridOptionsPanel,
                gridEventsPanel,
                gridEventsPro,
                print,
                selectRecords,
                proRemoveRowEvent,
                proEditRowEvent,
                proSaveRowEvent,
                panelEditRowEvent,
                panelSaveRowEvent,
                panelRemoveRowEvent,
                printStoreData,
                designTemplate,
                printTemplateDesign,
                editActivedEvent,
                disabledProviderId,
                panelModalVisible,
                providerModalVisible,
                modalValue,
                panelRecord,
                modalValuePro,
                panelRecordPro,
                importRef,
                handleQuery,
            };
        },
    });
</script>
